# -*- coding: utf-8 -*-
# @Time : 2025/1/23 14:33 
# @Author : SHGZ
# @File : runner_feishu.py.py



import os
import time
import requests
from common.mail import Mail
from common.result import Result
from excel_ddt import ddt
from get_path import get_pathdir

if __name__ == '__main__':
    os.system('rd /s /q result')
    os.system('rd /s /q report')

    # 执行并生成allure格式的测试结果

    ddt.run_web_cases()
    time.sleep(1)
    os.system('allure generate result -o report --clean')
# 把报告发布出来
#     os.system('allure serve ./result')
    url = 'https://open.feishu.cn/open-apis/bot/v2/hook/3cfe9125-a44b-49b4-af0b-09ad73de6044'
    method = 'post'
    headers = {'Content-Type': 'application/json'}
    sendmail = Mail()
    # # 处理相对路径为绝对路径
    sendmail.mail_info['filepaths'] = [get_pathdir + '\\lib\\cases\\result-广告批创.xlsx']
    sendmail.mail_info['filenames'] = ['result-广告批创.xlsx']
    res = Result()
    result = res.get_res('\\lib/cases\\result-广告批创.xlsx')
    print(result)
    runtype = result.get("runtype")
    title = result.get("title")
    starttime = result.get("starttime")
    endtime = result.get("endtime")
    casecount = result.get("casecount")
    passrate = result.get("passrate")
    status=result.get("status")
    #飞书配置
    if status == 'PASS':
        BUILD_STATUS = "成功"
    else:
        BUILD_STATUS = "失败"
    BUILD_NUMBER="xxx"
    JOB_NAME='腾讯批创自动化测试'
    JOB_URL="http://localhost:63342/webautonew/report/index.html"
    sheet_groups = res.get_groups_sheet('\\lib\\cases\\result-广告批创.xlsx')[0:]
    print(f"sheet_groups:{sheet_groups}")
    content = ""
    if status == 'PASS':
        content = f"第{BUILD_NUMBER}次构建，构建结果：<font color='green'> {BUILD_STATUS}</font>  \n" \
                  f"测试类型：{runtype}\n" \
                  f"测试标题：{title}\n" \
                  f"测试状态：<font color='green'>{status}</font>\n" \
                  f"总用例数：{casecount}\n" \
                  f"通过率：<font color='green'>{passrate}</font>\n" \
                  f"开始时间：{starttime}\n" \
                  f"结束时间：{endtime}\n" \
                  "\n " \
                  " \n" \
                  f"**----------------------------------以下是测试结果汇总----------------------------------** \n" \

    if status != 'PASS':
            content = f"第{BUILD_NUMBER}次构建，构建结果：<font color='red'> {BUILD_STATUS}</font>  \n" \
                      f"测试类型：{runtype}\n" \
                      f"测试标题：{title}\n" \
                      f"测试状态：<font color='red'>{status}</font>\n" \
                      f"总用例数：{casecount}\n" \
                      f"通过率：<font color='red'>{passrate}</font>\n" \
                      f"开始时间：{starttime}\n" \
                      f"结束时间：{endtime}\n" \
                      "\n " \
                      " \n" \
                      f"**----------------------------------以下是测试结果汇总----------------------------------** \n" \

    if len(sheet_groups) > 0:
        content += "**                           分组信息                             用例总数                  通过数                状态  **\n"
        for groups in sheet_groups:
            sheet_name = groups[0]
            content += f"**<font size='100' color='yellow'>模块名：【{sheet_name}】，用例如下：</font> **\n"
            print(f"sheet_name:{sheet_name}")
            sheet_cases = groups[1:]
            print(f"sheet_cases:{sheet_cases}")
            for cases in sheet_cases:
                group_info = cases[0]
                len_blank = 20 - len(group_info)
                case_num = cases[1]
                pass_num = cases[2]
                status = cases[3]
                if status == "PASS":
                    content += f"{group_info}" + len_blank * "---" + f"{case_num}                      {pass_num}                 <font color='green'>{status}</font>    \n"
                else:
                    content += f"{group_info}" + len_blank * "---" + f"{case_num}                      {pass_num}                 <font color='red'>{status}</font>    \n"
            content += "                                                                            \n"
            content += "**   ***************************************************************   ** \n"
            content += "                                                                            \n"


    with open(get_pathdir + r'\lib\module1.html', mode='r', encoding='utf8') as f:
        text = f.read()
        if status=="FAIL":
            text = text.replace("scolor", "red")
        else:
            text = text.replace("scolor", "green")
        text = text.replace("status", f"{status}")
        text = text.replace("passrate", f"{passrate}")
        text = text.replace("casecount", f"{casecount}")
        text = text.replace("endtime", f"{endtime}")
        text = text.replace("starttime", f"{starttime}")
        text = text.replace("title", f"{title}")
        text = text.replace("runtype", f"{runtype}")
    raw_index = ""
    groups = res.get_groups('\\lib\\cases\\result-广告批创.xlsx')[1:]
    print(groups)

    for group in groups:
        index_text = '<tr><td width="100" height="28" align="center" bgcolor="#FFFFFF" style="border:1px solid #ccc;">分组信息</td><td width="80" height="28" align="center" bgcolor="#FFFFFF" style="border:1px solid #ccc;">用例总数</td><td width="80" align="center" bgcolor="#FFFFFF" style="border:1px solid #ccc;">通过数</td><td width="80" align="center" bgcolor="#FFFFFF" style="border:1px solid #ccc;color: green;">状态</td></tr>'
        group_info = group[0]
        len_blank = 20 - len(group_info)
        case_num = group[1]
        pass_num = group[2]
        status = group[3]
        index_text = index_text.replace("分组信息", f"{group_info}")
        index_text = index_text.replace("用例总数", f"{case_num}")
        index_text = index_text.replace("通过数", f"{pass_num}")
        if status=="FAIL":
            index_text = index_text.replace('green', "red")
        index_text = index_text.replace("状态", f"{status}")
        raw_index += index_text
        # print("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&")
        # print(raw_index)
        # print("&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&")
    text = text.replace("mailbody", raw_index)

    sendmail.send(text)
    data = {
        "msg_type": "interactive",
        "card": {
            "config": {
                "wide_screen_mode": True,
                "enable_forward": True
            },
            "elements": [{
                "tag": "div",
                "text": {
                    "content": content,  # 这是卡片的内容，也可以添加其他的内容：比如构建分支，构建编号等
                    "tag": "lark_md"
                }
            }, {
                "actions": [{
                    "tag": "button",
                    "text": {
                        "content": "查看allure测试报告",  # 这是卡片的按钮，点击可以跳转到url指向的allure路径
                        "tag": "lark_md"
                    },
                    "color": "green",
                    "url": f"{JOB_URL}",  # JOB_URL 调用python定义的变量，该url是服务器下的allure路径
                    "type": "default",
                    "value": {}
                }],
                "tag": "action"
            }],
            "header": {
                "title": {
                    "content": JOB_NAME + "构建报告",  # JOB_NAME 调用python定义的变量，这是卡片的标题
                    "tag": "plain_text"
                }
            }
        }
    }
    res = requests.request(method=method, url=url, headers=headers, json=data)
    print(res)
    print(res.json())








